package com.zyk.scaffold.tcp.session;

import com.zyk.scaffold.tcp.connector.Connection;
import com.zyk.scaffold.tcp.connector.TcpConnectionManager;
import com.zyk.scaffold.tcp.listener.SessionListener;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Session {
    private String id;
    private Boolean enable = Boolean.TRUE;
    private LocalDateTime lastAccessedTime;
    private LocalDateTime createdTime;
    private Connection connection;
    private SessionListener sessionListener;
    private TcpConnectionManager tcpConnectionManager;
    SessionConfig sessionConfig = new SessionConfig();

    public Session(SessionListener sessionListener, SessionConfig sessionConfig, TcpConnectionManager tcpConnectionManager) {
        this.sessionListener = sessionListener;
        this.sessionConfig = sessionConfig;
        this.tcpConnectionManager = tcpConnectionManager;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Boolean isEnable() {
        return enable;
    }

    public void setEnable(Boolean enable) {
        this.enable = enable;
    }

    public LocalDateTime getLastAccessedTime() {
        return lastAccessedTime;
    }

    public void setLastAccessedTime(LocalDateTime lastAccessedTime) {
        this.lastAccessedTime = lastAccessedTime;
    }

    public LocalDateTime getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(LocalDateTime createdTime) {
        this.createdTime = createdTime;
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public void distory() {
        tcpConnectionManager.close(getId());
        close();
    }

    public void close() {
    }

    /**
     * 超时判断
     * @return
     */
    public boolean expire() {
        return LocalDateTime.now().minus(sessionConfig.getExpireTime(), ChronoUnit.MILLIS).isAfter(lastAccessedTime);
    }


    /**
     * 优化批量判断超时
     * @param target
     * @return
     */
    public boolean beforAccessed(LocalDateTime target) {
        return lastAccessedTime.isBefore(target);
    }

    public void refreshLastAccessedTime() {
        lastAccessedTime = LocalDateTime.now();
    }
}
